package interface_layer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database_layer.Common;
import database_layer.UpdateDispatcher;
import processing_layer.User;

/**
 * This servlet handles the registration of users to the web service.
 * It handles the form after a validation on the user side using javascript.
 * After a user is registered, he is logged in immediately.
 */
public class Registration extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Registration() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String repassword = request.getParameter("repassword");
			String firstName = request.getParameter("firstname");
			String lastName = request.getParameter("lastname");
			String phonePrefix = request.getParameter("phonepre");
			String phoneSuffix = request.getParameter("phonesuf");
			String address = request.getParameter("address");
			String adminAuth = request.getParameter("authenticationcode");
			String adminCheckbox = request.getParameter("admin");
			boolean isAdmin = (adminCheckbox == null ? false : true);
			int result = 0;
			
			// Add legality check
			if ( null == username || null == password || null == repassword || 
				 null == firstName|| null == lastName || null == phonePrefix || null == phoneSuffix || 
				 username.equals("") || password.equals("") || repassword.equals("") || 
				 firstName.equals("")|| lastName.equals("") || phonePrefix.equals("") || phoneSuffix.equals("") ) 
			{
				request.getSession().setAttribute("Error","Please fill all fields.");
				response.sendRedirect("register.jsp");
			}
			else if ( !(password.equals(repassword)) )
			{
				request.getSession().setAttribute("Error","Passwords doesn't match.");
				response.sendRedirect("register.jsp");
				return;
			}
			try
			{
				Long.parseLong(phonePrefix);
				Long.parseLong(phoneSuffix);
				if ( (phonePrefix.length() > 4) || (phoneSuffix.length() > 7) )//phone checks
				{
					request.getSession().setAttribute("Error","Phone number entered too long and invalid.");
					response.sendRedirect("register.jsp");
					return;
				}
			}
			catch (Exception e)
			{
				request.getSession().setAttribute("Error","Please insert only digits for phone number.");
				response.sendRedirect("register.jsp");
				return;
			}
			if ( isAdmin )
			{
				if ( (null == adminAuth) || !(Common.adminAuthentication.equals(adminAuth)) )
				{
					request.getSession().setAttribute("Error","Bad Admin password.");
					response.sendRedirect("register.jsp");
					return;
				}
			}
			if ( (null == address) || address.equals("") )
			{
				address = "None";
			}
			User newUser = new User(username, password, firstName, lastName, phonePrefix+phoneSuffix, address, isAdmin, null);
	
			result = UpdateDispatcher.addUser(newUser);
			if (Common.ENTRY_EXISTS == result)
			{
				// Add user already exists
				request.getSession().setAttribute("Error","Try different user name, the selected user already exists");
				response.sendRedirect("register.jsp");
				return;
			}
			
			else if (Common.INTERNAL_DB_ERROR == result)
			{
				// Add print cant register for now
				request.getSession().setAttribute("Error","Can't register now, Try again later.");
				response.sendRedirect("index.jsp");
				return;
			}
			
			else
			{
				// Create a session and log the user to the site and set the user type and name
				if ( database_layer.Common.NO_ERROR != processing_layer.SessionTracker.addConnectedUser(username) )
				{
					request.getSession().setAttribute("Error","The selected user already exists");
					response.sendRedirect("register.jsp");
					return;
				}
				request.getSession().setAttribute("username", username);
				if (isAdmin)
				{
					request.getSession().setAttribute("userType", Common.adminType);
				}
				else
				{
					request.getSession().setAttribute("userType", Common.studentType);	
				}			
				response.sendRedirect("index.jsp");
				return;
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	{
		doGet(request,response);
	}

}
